"""
客户门户管理层
负责客户门户相关的业务逻辑
"""

import stripe
import logging
from datetime import datetime
from typing import Dict, Any
from fastapi import HTTPException

from services.customer_service import CustomerService
from utils.config import Config

logger = logging.getLogger(__name__)


class PortalManager:
    """客户门户管理层"""
    
    def __init__(self, customer_service: CustomerService):
        self.customer_service = customer_service
    
    def create_portal_session(self, customer_id: str, return_url: str = None) -> Dict[str, Any]:
        """创建客户门户会话"""
        try:
            # 验证客户是否存在
            self.customer_service.reload_data()
            customer = self.customer_service.get_customer(customer_id)
            if not customer:
                raise HTTPException(status_code=404, detail="客户不存在")
            
            # 使用默认返回URL如果没有提供
            if not return_url:
                return_url = Config.DEFAULT_PORTAL_RETURN_URL
            
            # 创建 Customer Portal 会话
            session = stripe.billing_portal.Session.create(
                customer=customer['stripe_customer_id'],
                return_url=return_url
            )
            
            logger.info(f"Customer Portal 会话创建成功: {session.id} 客户: {customer_id}")
            
            return {
                "session_id": session.id,
                "url": session.url,
                "customer_id": customer_id
            }
            
        except stripe.error.StripeError as e:
            logger.error(f"Stripe错误: {str(e)}")
            raise HTTPException(status_code=400, detail=f"Stripe错误: {str(e)}")
        except Exception as e:
            logger.error(f"创建 Portal 会话失败: {str(e)}")
            raise HTTPException(status_code=500, detail="创建 Portal 会话失败")
    
    def get_portal_return_info(self) -> Dict[str, Any]:
        """获取门户返回信息"""
        return {
            "status": "success",
            "message": "订阅管理完成！",
            "timestamp": datetime.now().isoformat()
        }
    
    def get_subscription_cancel_info(self) -> Dict[str, Any]:
        """获取订阅取消信息"""
        return {
            "status": "cancelled",
            "message": "订阅支付已取消",
            "timestamp": datetime.now().isoformat()
        }
